package com.authine.cloudpivot.ext.applicationservice;

import com.alibaba.cola.dto.SingleResponse;
import com.authine.cloudpivot.ext.applicationservice.base.ApplicationBaseService;
import com.authine.cloudpivot.ext.constants.ModelConst;
import com.authine.cloudpivot.ext.dto.ContractClauseDto;
import com.authine.cloudpivot.ext.dto.ContractOrderIntentionDto;
import com.authine.cloudpivot.ext.service.ContractService;
import com.authine.cloudpivot.ext.service.OrderService;
import com.authine.cloudpivot.ext.service.impl.ContractServiceImpl;
import com.authine.cloudpivot.ext.service.impl.OrderServiceImpl;
import com.authine.cloudpivot.ext.utils.BoResultFormat;
import com.authine.cloudpivot.ext.utils.JdbcTemplateUtils;
import com.authine.cloudpivot.ext.utils.StringUtils;
import com.authine.common.json.JsonUtils;
import com.authine.mvp.app.launcher.domain.utills.ApplicationContextUtils;
import com.authine.mvp.app.launcher.dto.bo.response.BO;
import com.authine.mvp.app.launcher.dto.bo.response.BOList;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.util.CollectionUtils;

import javax.ws.rs.POST;
import javax.ws.rs.Path;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.authine.hermes.app.launcher.service.ApplicationServiceFoundation.CUSTOM_SERVICE;

/**
 * @ClassName TransferManageOrderService
 * @Description: 代购合同自定义服务
 * @Author cjj
 * @Date 2021/6/18
 * @Version V1.0
 **/
@Path("PurchaseContractService")
@Slf4j
public class PurchaseContractService extends ApplicationBaseService {
    private OrderService orderService = new OrderServiceImpl();
    private ContractService contractService = new ContractServiceImpl();
    private NamedParameterJdbcTemplate jdbcTemplate = ApplicationContextUtils.getBean(NamedParameterJdbcTemplate.class);

    /**
     * 代购合同-全部-创建代购意向
     *
     * @param dto
     * @return
     */
    @Path("createIntention")
    @POST
    @Operation(summary = "代购合同-全部-创建代购意向", tags = CUSTOM_SERVICE, description = "projectName必填")
    public SingleResponse<BO> createIntention(@Parameter ContractOrderIntentionDto dto) {
        if (StringUtils.isBlank(dto.getProjectName())) {
            return SingleResponse.buildFailure("-1", "项目名称必填");
        }
        return contractService.saveIntention(dto);
    }

    /**
     * 代购合同-全部-创建代购合同-保存合同
     *
     * @param dto
     * @return
     */
    @Path("saveContract")
    @POST
    @Operation(summary = "代购合同-全部-创建代购合同-保存合同", tags = CUSTOM_SERVICE, description = "id、contractClause、contractGoods必填")
    public SingleResponse<BO> saveContract(@Parameter ContractOrderIntentionDto dto) {
        if (StringUtils.isBlank(dto.getId())) {
            return SingleResponse.buildFailure("-1", "代购意向ID必填");
        }
        if (CollectionUtils.isEmpty(dto.getContractClause())) {
            return SingleResponse.buildFailure("-1", "代购条款必填");
        }
        if (CollectionUtils.isEmpty(dto.getContractGoods())) {
            return SingleResponse.buildFailure("-1", "代购商品必填");
        }
        return contractService.saveIntentionContract(dto);
    }

    /**
     * 代购合同-全部-创建代购合同-查询创建合同列表
     *
     * @param dto
     * @return
     */
    @Path("contractList")
    @POST
    @Operation(summary = "代购合同-全部-创建代购合同-查询创建合同列表/代购合同-全部-详情/代购合同-进行中-详情/代购合同-已完成-详情", tags = CUSTOM_SERVICE, description = "id必填")
    public SingleResponse<BO> contractList(@Parameter ContractOrderIntentionDto dto) {
        if (StringUtils.isBlank(dto.getId())) {
            return SingleResponse.buildFailure("-1", "代购意向ID必填");
        }
        //代购意向数据
        Map<String, Object> contractOrderIntention = selectModelById(dto.getId(), ModelConst.T_CONTRACT_ORDER_INTENTION);
        if (CollectionUtils.isEmpty(contractOrderIntention)) {
            return SingleResponse.buildFailure("-1", "代购意向信息不存在");
        }
        //代购条款数据
        List<Map<String, Object>> contractClauses = JdbcTemplateUtils.builder(ModelConst.T_CONTRACT_CLAUSE).selectField(" * ")
                .eq("contract_intention_id", dto.getId()).queryForList();
        contractOrderIntention.put("contractClauseList", contractClauses);
        //代购商品数据
        List<Map<String, Object>> contractGoods = JdbcTemplateUtils.builder(ModelConst.T_CONTRACT_GOODS).selectField(" * ")
                .eq("contract_intention_id", dto.getId()).queryForList();
        contractOrderIntention.put("contractGoodsList", contractGoods);
        //构建结果集
        BO bo = new BO();
        bo.setSchemaCode(ModelConst.T_CONTRACT_ORDER_INTENTION);
        bo.setData(contractOrderIntention);
        return SingleResponse.of(bo);
    }

    /**
     * 代购合同-全部-创建代购合同-提交合同
     *
     * @param dto
     * @return
     */
    @Path("submitContract")
    @POST
    @Operation(summary = "代购合同-全部-创建代购合同-提交合同", tags = CUSTOM_SERVICE, description = "id、contractClause、contractGoods必填")
    public SingleResponse<BO> submitContract(@Parameter ContractOrderIntentionDto dto) {
        if (StringUtils.isBlank(dto.getId())) {
            return SingleResponse.buildFailure("-1", "项目名称必填");
        }
        if (CollectionUtils.isEmpty(dto.getContractClause())) {
            return SingleResponse.buildFailure("-1", "代购条款必填");
        }
        if (CollectionUtils.isEmpty(dto.getContractGoods())) {
            return SingleResponse.buildFailure("-1", "代购商品必填");
        }
        return contractService.createSubmitContract(dto);
    }

    /**
     * 代购合同-全部-确认代购合同
     *
     * @param dto
     * @return
     */
    @Path("confirmContract")
    @POST
    @Operation(summary = "代购合同-全部-确认代购合同", tags = CUSTOM_SERVICE, description = "id必填")
    public SingleResponse<BO> confirmContract(@Parameter ContractOrderIntentionDto dto) {
        if (StringUtils.isBlank(dto.getId())) {
            return SingleResponse.buildFailure("-1", "代购意向ID必填");
        }
        return contractService.confirmIntentionContract(dto.getId());
    }

    /**
     * 代购合同-全部-提交
     *
     * @param dto
     * @return
     */
    @Path("submitDelivery")
    @POST
    @Operation(summary = "代购合同-全部-提交", tags = CUSTOM_SERVICE, description = "ids必填")
    public SingleResponse<BO> submitDelivery(@Parameter ContractOrderIntentionDto dto) {
        if (CollectionUtils.isEmpty(dto.getIds())) {
            return SingleResponse.buildFailure("-1", "代购意向ID集合必填");
        }
        return contractService.submitIntentionContract(dto.getIds());
    }

    /**
     * 代购合同-进行中-确认进度
     *
     * @param dto
     * @return
     */
    /*@Path("confirmProgress")
    @POST
    @Operation(summary = "代购合同-进行中-确认进度", tags = CUSTOM_SERVICE, description = "customerOrderIds必填")
    public SingleResponse<BOList> confirmProgress(@Parameter ContractClauseDto dto) {
        if (CollectionUtils.isEmpty(dto.getCustomerOrderIds())) {
            return SingleResponse.buildFailure("-1", "客户订单ID集合必填");
        }
        String tableName = getTableName(ModelConst.T_ORDER_CUSTOMER_GOODS);
        String customerOrderIdsInSql = dto.getCustomerOrderIds().stream().map(s -> "\'" + s + "\'").collect(Collectors.joining(", "));
        String sql = " select * from " + tableName + " where order_customer_id in (" + customerOrderIdsInSql + ")";
        List<Map<String, Object>> orderCustomerGoodsList = jdbcTemplate.queryForList(sql, new HashMap<>());
        List<String> goodsIds = orderCustomerGoodsList.stream().map(t -> (String) t.get("id")).collect(Collectors.toList());
        List<Map<String, Object>> result = orderService.goodsReceiptBatch(goodsIds);
        //构建结果集
        BoResultFormat.resultFormat(result, ModelConst.T_ORDER_CUSTOMER_GOODS);
        BOList bolist = new BOList();
        bolist.setData(result);
        bolist.setTotal(result.size());
        bolist.setSchemaCode(ModelConst.T_ORDER_CUSTOMER_GOODS);
        return SingleResponse.of(bolist);
    }*/

    /**
     * 代购合同-进行中分页列表/代购合同-已完成分页列表
     *
     * @param dto
     * @return
     */
    @Path("contractClauseList")
    @POST
    @Operation(summary = "代购合同-进行中分页列表/代购合同-已完成分页列表", tags = CUSTOM_SERVICE, description = "pageIndex、pageSize、customerOrderStatus必填")
    public SingleResponse<BOList> contractClauseList(@Parameter ContractClauseDto dto) {
        log.info("------------------------代购合同-进行中分页列表/代购合同-已完成分页列表 contractClauseList Param：{}------------------------", JsonUtils.toJson(dto));
        if (null == dto.getPageIndex() || null == dto.getPageSize()) {
            return SingleResponse.buildFailure("-1", "pageIndex、pageSize必填");
        }
        if(StringUtils.isBlank(dto.getOrderCustomerStatus())){
            return SingleResponse.buildFailure("-1", "客户订单状态必填");
        }
        String clauseTableName = getTableName(ModelConst.T_CONTRACT_CLAUSE);
        String customerTableName = getTableName(ModelConst.T_ORDER_CUSTOMER);
        Map<String, Object> parameter = new HashMap<>();
        StringBuilder listSql = new StringBuilder();
        StringBuilder whereSql = new StringBuilder();
        StringBuilder countSql = new StringBuilder();
        listSql.append("select * from "+clauseTableName+" c " +
                "left join "+customerTableName+" oc on c.customer_order_id = oc.id " +
                "where c.deleted ='0'");
        countSql.append("select count(*) from "+clauseTableName+" c " +
                "left join "+customerTableName+" oc on c.customer_order_id = oc.id " +
                "where c.deleted ='0'");
        //拼接参数
        if (null != dto.getOrderCustomerStatus()) {
            whereSql.append(" and oc.order_customer_status = :order_customer_status ");
            parameter.put("order_customer_status", dto.getOrderCustomerStatus());
        }
        countSql.append(whereSql);
        listSql.append(whereSql);
        listSql.append(" order by c.createdTime desc");
        listSql.append(" limit " + dto.getPageIndex() * dto.getPageSize() + ", " + dto.getPageSize());
        log.info("------------------------代购合同-进行中分页列表/代购合同-已完成分页列表 contractClauseList listSql：{}------------------------parameter：{}", listSql, JsonUtils.toJson(parameter));
        List<Map<String, Object>> resultList = jdbcTemplate.queryForList(listSql.toString(), parameter);
        Integer count = 0;
        try {
            count = jdbcTemplate.queryForObject(countSql.toString(), parameter, Integer.class);
        } catch (DataAccessException e) {
            e.printStackTrace();
        }
        //构建结果集
        BoResultFormat.resultFormat(resultList, ModelConst.T_CONTRACT_CLAUSE);
        BOList bOList = new BOList();
        bOList.setData(resultList);
        bOList.setTotal(count);
        bOList.setSchemaCode(ModelConst.T_CONTRACT_CLAUSE);
        return SingleResponse.of(bOList);
    }
}
